import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:gif/gif.dart';
import 'package:vibration/vibration.dart';
import '../common/api_service.dart';

import '../common/utils.dart';
import '../widgets/typing_indicator.dart';

import '../common/audio_record_manager.dart';
import '../common/constants.dart';
import '../controllers/chat_controller.dart';

enum RecordState { none, started, recording, recognizing, finished, canceled }

class AudioRecordView extends StatefulWidget {
  const AudioRecordView({super.key});

  @override
  State<AudioRecordView> createState() => _AudioRecordViewState();
}

class _AudioRecordViewState extends State<AudioRecordView> with TickerProviderStateMixin {
  final controller = Get.find<ChatController>(tag: Get.arguments['pipeId']);
  final AudioRecordManager _audioRecorder = AudioRecordManager();
  late final GifController _gifController;
  final _textEditingController = TextEditingController();
  final _recordBtnKey = GlobalKey();
  Timer? _timer;
  var _desc = "按住说话";
  var _descColor = Colors.white54;
  var _isRecording = false;
  var _recordTime = "00:00";
  var _recordState = RecordState.none;
  var _voiceUrl = "";

  @override
  void initState() {
    super.initState();
    _gifController = GifController(vsync: this);
    _audioRecorder.openRecorder();
  }

  @override
  void dispose() {
    _stopTimer();
    _gifController.dispose();
    _audioRecorder.dispose();
    super.dispose();
  }

  void _startTimer() {
    _stopTimer();
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        _recordTime = formatSeconds(timer.tick);
      });
    });
  }

  void _stopTimer() {
    _timer?.cancel();
  }

  _startRecording() async {
    setState(() {
      _recordState = RecordState.started;
      _recordTime = "00:00";
      _desc = "请开始说话...";
      _descColor = Colors.white54;
      _isRecording = true;
    });
    _gifController.repeat(period: Duration(seconds: 2));
    _performHapticFeedback();
    _startTimer();
    await _audioRecorder.startRecording();
  }

  _stopRecording() async {
    setState(() {
      if (_recordState == RecordState.started || _recordState == RecordState.recording) {
        _recordState = RecordState.recognizing;
      }
      _desc = "按住说话";
      _descColor = Colors.white54;
    });
    _gifController.stop();
    _performHapticFeedback();
    _stopTimer();
    final filePath = await _audioRecorder.stopRecording();
    if (filePath != null) {
      _uploadAudioFile(filePath);
    }

    Future.delayed(Duration(seconds: 1), () {
      setState(() {
        if (_recordState == RecordState.recognizing) {
          _recordState = RecordState.finished;
        }
        _isRecording = false;
      });
    });
  }

  _resetAudioRecordState() {
    setState(() {
      _recordState = RecordState.none;
      _recordTime = "00:00";
      _textEditingController.text = '';
      _voiceUrl = "";
    });
  }

  _uploadAudioFile(String filePath) {
    ApiService().uploadAudio(filePath, (result) {
      //print(result);
      String voiceUrl = result["voiceUrl"];
      String voiceText = result["voiceText"];
      setState(() {
        _voiceUrl = voiceUrl;
        _textEditingController.text = voiceText;
      });
    }, () {});
  }

  void _performHapticFeedback() async {
    var hasVibrator = await Vibration.hasVibrator() ?? false;
    if (hasVibrator) {
      await Vibration.vibrate(duration: 50, amplitude: 100);
    }
  }

  _buildAudioAnimation() {
    return Column(
      children: [
        if (_recordState == RecordState.recognizing)
          Container(
            decoration: BoxDecoration(
              color: Colors.white24,
              borderRadius: BorderRadius.circular(18),
            ),
            margin: EdgeInsets.only(left: 12, top: 0, right: 12, bottom: 10),
            padding: EdgeInsets.symmetric(horizontal: 12),
            width: double.infinity,
            height: 36,
            child: Row(
              children: [
                Text(
                  "识别中",
                  style: TextStyle(color: Colors.white),
                ),
                SizedBox(
                  width: 5,
                ),
                TypingIndicator2()
              ],
            ),
          ),
        Container(
          decoration: BoxDecoration(
            color: _descColor == Colors.red ? Colors.red : Colors.black,
            borderRadius: BorderRadius.circular(18),
          ),
          height: 36,
          margin: EdgeInsets.symmetric(horizontal: 12),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Gif(
                controller: _gifController,
                image: const AssetImage('assets/images/icon_long_audio_play_animation_dark.webp'),
                width: 70,
                fit: BoxFit.cover,
              ),
              SizedBox(
                width: 10,
              ),
              Text(
                _recordTime,
                style: TextStyle(color: Colors.white),
              ),
              SizedBox(
                width: 10,
              ),
              Gif(
                controller: _gifController,
                image: const AssetImage('assets/images/icon_long_audio_play_animation_dark.webp'),
                width: 70,
                fit: BoxFit.cover,
              ),
            ],
          ),
        )
      ],
    );
  }

  _buildVoiceRecordView() {
    return Stack(
      children: [
        if (!_isRecording)
          Positioned(
            left: 10,
            top: 100,
            child: GestureDetector(
              child: Container(
                decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: Colors.white24, width: 1)),
                padding: const EdgeInsets.all(8.0),
                child: const Icon(
                  CupertinoIcons.back,
                  size: 28,
                  color: Colors.white,
                ),
              ),
              onTap: () {
                controller.inputType.value = "str";
              },
            ),
          ),
        Column(
          children: [
            Padding(
              padding: EdgeInsets.only(top: 15, bottom: 15),
              child: _isRecording
                  ? _buildAudioAnimation()
                  : SizedBox(
                      width: double.infinity,
                      height: 36,
                    ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 10),
              child: Text(
                _desc,
                style: TextStyle(color: _descColor),
              ),
            ),
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              child: Opacity(
                opacity: (_recordState == RecordState.started || _recordState == RecordState.recording) ? 0.8 : 1.0,
                child: Container(
                  key: _recordBtnKey,
                  decoration: BoxDecoration(color: Constants.themeColor, shape: BoxShape.circle),
                  padding: const EdgeInsets.all(16.0),
                  child: const Icon(
                    Icons.mic,
                    size: 48,
                    color: Colors.white,
                  ),
                ),
              ),
              onLongPressStart: (details) {
                _startRecording();
              },
              onLongPressMoveUpdate: (details) {
                // 获取录音按钮的 RenderBox
                final RenderBox? box = _recordBtnKey.currentContext?.findRenderObject() as RenderBox?;
                if (box == null) return;

                // 计算按钮的边界
                final Offset buttonPosition = box.localToGlobal(Offset.zero);
                final Size buttonSize = box.size;

                // 创建按钮的矩形区域
                final Rect buttonRect = Rect.fromLTWH(
                  buttonPosition.dx,
                  buttonPosition.dy,
                  buttonSize.width,
                  buttonSize.height,
                );

                // 检查手指位置是否在按钮区域内
                if (!buttonRect.contains(details.globalPosition)) {
                  setState(() {
                    _desc = "松开取消发送";
                    _descColor = Colors.red;
                    _recordState = RecordState.canceled;
                  });
                } else {
                  setState(() {
                    _desc = "请开始说话...";
                    _descColor = Colors.white54;
                    _recordState = RecordState.recording;
                  });
                }
              },
              onLongPressEnd: (details) {
                _stopRecording();
              },
            )
          ],
        )
      ],
    );
  }

  _buildSendVoiceView() {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 12),
          child: TextField(
            controller: _textEditingController,
            keyboardType: TextInputType.multiline,
            style: TextStyle(color: Colors.white, fontSize: 15),
            cursorColor: Colors.white,
            maxLines: 5,
            minLines: 1,
            decoration: InputDecoration(
              isDense: true,
              filled: true,
              fillColor: Colors.white24,
              contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(20),
                borderSide: BorderSide.none,
              ),
            ),
          ),
        ),
        SizedBox(
          height: 15,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Gif(
              image: const AssetImage('assets/images/icon_long_audio_play_animation_dark.webp'),
              width: 70,
              fit: BoxFit.cover,
            ),
            SizedBox(
              width: 10,
            ),
            Text(
              _recordTime,
              style: TextStyle(color: Colors.white),
            ),
            SizedBox(
              width: 10,
            ),
            Gif(
              image: const AssetImage('assets/images/icon_long_audio_play_animation_dark.webp'),
              width: 70,
              fit: BoxFit.cover,
            ),
          ],
        ),
        SizedBox(
          height: 10,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            _buildButtonItem("icon_cancel_audio_record.png", "取消", () {
              _resetAudioRecordState();
            }),
            _buildButtonItem("icon_only_audio.png", "仅发语音", () {
              controller.sendAudioMessage(_voiceUrl, '');
              _resetAudioRecordState();
            }),
            _buildButtonItem("icon_only_text.png", "仅发文字", () {
              if (_textEditingController.text.isEmpty) {
                Fluttertoast.showToast(msg: "文字内容为空", gravity: ToastGravity.CENTER);
                return;
              }
              controller.sendAudioMessage('', _textEditingController.text);
              _resetAudioRecordState();
            }),
            _buildButtonItem("icon_send_audio_and_text.png", "语音加文字", () {
              if (_textEditingController.text.isEmpty) {
                Fluttertoast.showToast(msg: "文字内容为空", gravity: ToastGravity.CENTER);
                return;
              }
              controller.sendAudioMessage(_voiceUrl, _textEditingController.text);
              _resetAudioRecordState();
            }),
          ],
        )
      ],
    );
  }

  _buildButtonItem(String imageName, String title, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 12),
        child: Column(
          children: [
            Image.asset(
              "assets/images/$imageName",
              width: 50,
              height: 50,
              fit: BoxFit.cover,
            ),
            Text(
              title,
              style: TextStyle(color: Colors.grey, fontSize: 12),
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final bottomPadding = MediaQuery.of(context).padding.bottom;
    return Container(
      padding: EdgeInsets.only(left: 10, top: 10, right: 0, bottom: bottomPadding + 60),
      color: Colors.black,
      width: double.infinity,
      child: _recordState == RecordState.finished ? _buildSendVoiceView() : _buildVoiceRecordView(),
    );
  }
}
